package com.example.personblog.controller;

import com.example.personblog.common.Result;
import com.example.personblog.entity.Post;
import com.example.personblog.service.PostService;
import com.example.personblog.service.LikeService;
import com.example.personblog.utils.MinioUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestPart;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private MinioUtil minioUtil;

    @GetMapping
    public Result<List<Post>> getAllPosts() {
        return Result.success(postService.getAllPosts());
    }

    @GetMapping("/{id}")
    public Result<Post> getPostById(@PathVariable Long id) {
        try {
            Post post = postService.getPostById(id);
            // 先获取当前数据
            Long currentViews = post.getViews();
            // 增加浏览量并保存到数据库
            post.setViews(currentViews + 1);
            postService.updatePost(post, post.getUserId());
            return Result.success(post);
        } catch (Exception e) {
            return Result.error("获取文章详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建帖子
     */
    @PostMapping
    public Result<Post> createPost(
            @RequestPart(value = "cover", required = false) MultipartFile cover,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam("status") Integer status,
            HttpServletRequest request) {

        try {
            Long userId = (Long) request.getAttribute("userId");
            System.out.println("Current userId from token: " + userId); // 添加调试日志

            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }

            Post post = new Post();
            post.setTitle(title);
            post.setContent(content);
            post.setStatus(status);
            post.setUserId(userId);

            // 如果有封面，先上传封面
            if (cover != null && !cover.isEmpty()) {
                String coverUrl = minioUtil.uploadCover(cover);
                post.setCover(coverUrl);
            }

            Post savedPost = postService.createPost(post, userId);
            return Result.success(savedPost);
        } catch (Exception e) {
            System.out.println("创建文章失败，错误信息：" + e.getMessage());
            e.printStackTrace();
            return Result.error("创建文章失败：" + e.getMessage());
        }
    }


    /**
     * 点赞
     */
    @PostMapping("/{id}/like")
    public Result<Map<String, Object>> like(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 获取当前用户ID
            Long userId = (Long) request.getAttribute("userId");
            log.info("Current userId from token: {}", userId);
            System.out.println(userId);
            if (userId == null) {
                return Result.error("请先登录");
            }

            Post post = postService.getPostById(id);
            if (post == null) {
                return Result.error("文章不存在");
            }

            // 增加点赞数
            post.setLikes(post.getLikes() + 1);
            // 保存更新后的文章
            postService.updatePost(post, post.getUserId());

            Map<String, Object> result = new HashMap<>();
            result.put("likeCount", post.getLikes());
            result.put("views", post.getViews());

            return Result.success(result);
        } catch (Exception e) {
            System.out.println("点赞失败：" + e.getMessage());
            e.printStackTrace();
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    /**
     * 获取文章最新统计数据
     */
    @GetMapping("/{id}/stats")
    public Result<Map<String, Object>> getPostStats(@PathVariable Long id) {
        try {
            Post post = postService.getPostById(id);
            Map<String, Object> stats = new HashMap<>();
            stats.put("views", post.getViews());
            stats.put("likes", post.getLikes());
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取文章列表
     */
    @GetMapping("/page")
    public Result<Page<Post>> getPostsByPage(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "1") Integer status) {

        return Result.success(postService.getPostsByPage(page, size, status));
    }

    /**
     * 搜索文章
     */
    @GetMapping("/search")
    public Result<Page<Post>> searchPosts(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        return Result.success(postService.searchPosts(keyword, page, size));
    }
}